package com.atguigu.gulimall.search.service.impl;

import com.alibaba.fastjson.JSON;

import com.alibaba.nacos.client.utils.JSONUtils;
import com.atguigu.common.to.es.SkuEsModel;
import com.atguigu.gulimall.search.config.ElasticSearchConfig;
import com.atguigu.gulimall.search.constant.EsConstant;
import com.atguigu.gulimall.search.service.ProductSaveService;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
@Slf4j
@Service
public class ProductSaveServiceImpl implements ProductSaveService {


   @Autowired
   RestHighLevelClient client;

    /**
     * 存入 商品的sku 进入es
     * @param skuEsModelList
     */
    @Override
    public boolean saveProductUp(List<SkuEsModel> skuEsModelList) throws IOException {
        BulkRequest bulkRequest = new BulkRequest();

        for (SkuEsModel skuEsModel : skuEsModelList) {
           // 指定每一条数据存入的 索引
            IndexRequest indexRequest = new IndexRequest(EsConstant.PRODUCT_INDEX);
           indexRequest.id(skuEsModel.getSkuId().toString());
            String modelJson = JSON.toJSONString(skuEsModel);
            indexRequest.source(modelJson, XContentType.JSON);
            bulkRequest.add(indexRequest);
        }


        // 一次性存入 多条数据
        BulkResponse bulk = client.bulk(bulkRequest, ElasticSearchConfig.COMMON_OPTIONS);
        boolean flag = bulk.hasFailures();

        // 也可以对 数据进行流式处理
        List<String> collect = Arrays.stream(bulk.getItems()).map((item) -> {
            return item.getId();
        }).collect(Collectors.toList());

        if(flag==true){
            log.info("上传错误的是{}",collect);
        }
      return !flag;
    }
}
